<template>
    <page-meta :page-style="'overflow:' + (showdialog ? 'hidden' : 'visible')"> </page-meta>
    <view class="order-detail-main">
        <!--  -->
        <NavBar :title="pageTitle" :isBack="true" bgColor="#fe292b" />
        <view class="order-detail-content">
            <!-- 状态信息 -->
            <view class="goods-status-info">
                <view class="goods-status">
                    <view class="goods-status-name">
                        {{ translateOrderCode(Data.orderStatus, Data.isSelfPickup) }}
                    </view>
                    <image class="goods-status-img" :src="getStatusImg(Data.orderStatus)"></image>
                </view>
                <view class="goods-status-desc" v-if="Data.orderStatus == 1">
                    <view
                        v-if="checkCountdow(Data.detailInfo.createdAt, Data.detailInfo.autoCancelMinutes)"
                        class="goods-status-desc">
                        <text>请在</text>
                        <CountDown
                            :endTime="
                                getTimeStamp(Data.detailInfo.createdAt, 60000 * Data.detailInfo.autoCancelMinutes)
                            " />
                        <text>内完成支付超时将自动取消订单</text>
                    </view>
                </view>
                <!-- 显示状态原因（流程待优化） -->
                <view class="goods-status-desc" v-if="getRemarkShow">{{ getRemarkShow }} </view>
            </view>
            <view v-if="Data.isSelfPickup">
                <div v-if="!props.type">
                    <Address :addressInfo="Data.detailInfo.selfLiftSite" :showDistance="false"></Address>
                    <view class="order-info">
                        <view class="order-info-item">
                            <view class="order-info-large-label">联系人</view>
                            <view class="order-info-large-text">
                                <test>
                                    {{ Data.detailInfo.consigneeInfo?.consigneeName }}
                                    {{ Data.detailInfo.consigneeInfo?.consigneeMobile }}
                                </test>
                            </view>
                        </view>
                    </view>
                </div>
                <view v-else>
                    <view class="order-info bottom-bg">
                        <view class="order-info-item">
                            <view class="order-info-large-label">自提点</view>
                            <view class="order-info-large-text">
                                {{ Data.detailInfo.selfLiftSite?.selfLiftName }}
                            </view>
                        </view>
                    </view>
                    <view class="order-info">
                        <view class="order-info-item">
                            <view class="order-info-large-label">联系人</view>
                            <view class="order-info-large-text">
                                <test>
                                    {{ Data.detailInfo.consigneeInfo?.consigneeName }}
                                    {{ Data.detailInfo.consigneeInfo?.consigneeMobile }}
                                </test>
                                <view class="address_icon_img relative">
                                    <image src="/static/marker/dianhua.png"></image>
                                    <view class="address_call_block" @click.stop="copyPhone"></view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 用户地址信息(虚拟商品没有收货地址) -->
            <view v-else>
                <view class="address-info" v-if="Data.detailInfo.consigneeName">
                    <view>
                        <view class="address-text">
                            {{ Data.detailInfo.consigneeProvince }}{{ Data.detailInfo.consigneeCity
                            }}{{ Data.detailInfo.consigneeCounty }}{{ Data.detailInfo.consigneeAddress }}
                        </view>
                        <view class="address-phone">
                            {{ Data.detailInfo.consigneeName }} {{ Data.detailInfo.consigneeMobile }}
                        </view>
                    </view>
                </view>
            </view>

            <!-- 商品信息 -->
            <view class="goods-info">
                <view v-for="item in Data.goodsList" :key="item.id" class="goods-top">
                    <GoodsCard
                        :showRefundTag="props.type && Data.isSelfPickup"
                        :orderType="Data.orderType"
                        :goodsData="item"
                        @handleGoodsCardClick="clickShopCard" />
                </view>
                <view class="goods-center">
                    <!-- 上门自提订单交易完成后不再展示“售后”入口 -->
                    <view
                        class="goods-center-btn"
                        v-if="Data.orderStatus > 1 && Data.orderStatus <= 5 && !isFinished && !props.type"
                        @click="clickRefund">
                        售后
                    </view>
                    <view
                        v-if="Data.detailInfo.spellOrderId && Data.orderStatus === 6"
                        class="goods-center-btn-grow"
                        @click="gotoGrow(Data.detailInfo.spellOrderId)">
                        查看拼团详情
                    </view>
                </view>
                <view class="goods-bottom">
                    <view class="goods-bottom-item">
                        <view>商品总价</view>
                        <view class="right-text">
                            <text v-if="Data.orderType === 6">
                                <text v-if="goodsTotal > 0"> {{ floatDivide(goodsTotal, 100) }}元+</text>
                                <text>{{ floatDivide(Data.detailInfo.totalPoints, 100) }}积分</text>
                            </text>
                            <text v-else>￥{{ floatDivide(goodsTotal, 100) }}</text>
                        </view>
                    </view>
                    <!-- 虚拟商品订单不显示运费  上面自提订单没有运费-->
                    <view
                        class="goods-bottom-item"
                        v-if="
                            !(Data.orderType === 6 && Data.goodsList[0]?.goodsType > 1) &&
                            Data.orderType != 9 &&
                            !Data.isSelfPickup
                        ">
                        <view>运费</view>
                        <view class="right-text">
                            {{ Data.logisticsFee ? `${floatDivide(Data.logisticsFee, 100)}元运费` : 0 }}
                        </view>
                    </view>
                    <view v-if="showDiscount()" class="goods-bottom-item">
                        <view>{{ getDiscountName() }}</view>
                        <view class="right-text">
                            <view class="amount-total">-￥{{ floatDivide(showDiscount(), 100) }}</view>
                        </view>
                    </view>
                    <view v-if="Data.detailInfo.couponFee" class="goods-bottom-item">
                        <view>优惠券优惠</view>
                        <view class="amount-total">-￥{{ floatDivide(Data.detailInfo.couponFee, 100) }}</view>
                    </view>
                    <view v-if="Data.orderType === 6" class="goods-bottom-item">
                        <view>积分抵扣</view>
                        <view class="amount-total">-{{ floatDivide(Data.detailInfo.totalPoints, 100) }}积分</view>
                    </view>
                    <view
                        v-if="Data.orderType === 1 && Data.detailInfo.discountPropReducePrice"
                        class="goods-bottom-item">
                        <view>积分抵扣</view>
                        <view class="amount-total">
                            -￥{{ floatDivide(Data.detailInfo.discountPropReducePrice, 100) }}
                        </view>
                    </view>
                    <view class="goods-bottom-item">
                        <view>实付金额</view>
                        <view class="amount-total">
                            ￥{{ floatDivide(Data.detailInfo.orderAmountTotal, 100) || 0 }}
                        </view>
                    </view>
                </view>
            </view>
            <!-- 订单信息 -->
            <view class="order-info">
                <view class="order-info-item">
                    <view class="order-info-label">订单号</view>
                    <view class="order-info-text">
                        {{ Data.detailInfo.orderSn }}<text> |</text><text @click="copy" class="copy-text"> 复制</text>
                    </view>
                </view>
                <view class="order-info-item">
                    <view class="order-info-label">订单类型</view>
                    <view class="order-info-text">{{ getOrderType(Data.detailInfo.orderType) }}</view>
                </view>
                <view class="order-info-item">
                    <view class="order-info-label">付款方式</view>
                    <view class="order-info-text">{{ Data.detailInfo.payMethod }}</view>
                </view>
                <view class="order-info-item">
                    <view class="order-info-label">下单时间</view>
                    <view class="order-info-text">{{ Data.detailInfo.createdAt }}</view>
                </view>
                <view class="order-info-item">
                    <view class="order-info-label">付款时间</view>
                    <view class="order-info-text">{{ Data.detailInfo.payAt }}</view>
                </view>
                <view class="order-info-item">
                    <view class="order-info-label">备注</view>
                    <view class="order-info-text">{{ Data.detailInfo.buyerRemarks }}</view>
                </view>
            </view>
            <div
                style="height: 109rpx"
                v-if="
                    props.type == 1 ||
                    (props.type == 2 && Data.isSelfPickup && Data.orderStatus === 3) ||
                    ([3, 5, 1].includes(Number(Data.orderStatus)) && !props.type) ||
                    isLogistics
                "></div>
            <view v-if="props.type == 1" class="order-button-wrap order-button-wrap-sigle">
                <view class="order-button-single" @click="alertDialogHandler"> 确认核销 </view>
            </view>
            <view v-else class="order-button-wrap">
                <view v-if="props.type" class="order-button">
                    <view
                        class="order-button-item active"
                        v-if="Data.isSelfPickup && Data.orderStatus === 3"
                        @click="alertDialogHandler">
                        标记已提货
                    </view>
                </view>
                <view v-else class="order-button">
                    <view
                        class="order-button-item"
                        v-if="Data.orderStatus == 3 && !Data.isSelfPickup"
                        @click="clickReceipt">
                        确认收货
                    </view>
                    <view class="order-button-item" v-if="isLogistics && !Data.isSelfPickup" @click="toLogistics">
                        查看物流
                    </view>
                    <view class="order-button-item" v-if="Data.orderStatus == 1" @click="clickCancelOrder">
                        取消订单
                    </view>
                    <view class="order-button-item active" v-if="Data.orderStatus == 1" @click="toPay">付款</view>
                    <view
                        class="order-button-item"
                        v-if="Data.isSelfPickup && Data.orderStatus === 3"
                        @click="alertDialogHandler">
                        我已提货
                    </view>
                    <view
                        class="order-button-item active"
                        v-if="Data.orderStatus == 3 && Data.isSelfPickup"
                        @click="pickingCode">
                        查看提货码
                    </view>
                </view>
            </view>
        </view>
        <!-- 库存不足取消订单 -->
        <MessageBox
            ref="messagebox"
            :btnName="dialog.btnName"
            :content="dialog.content"
            @comfirm="messageBoxConfirm"></MessageBox>
        <!-- 弹框 -->
        <view class="popup-dialog" v-if="Data.receiptShow">
            <view class="popup-dialog-content">
                <view class="title">确认收货后，钱款将打给商户， 是否确认已收到货物？</view>
                <view class="button">
                    <view class="cancel" @click="Data.receiptShow = false">取消</view>
                    <view class="confirm" @click="confirmReceipt">确认</view>
                </view>
            </view>
        </view>
        <!-- 取消弹框 -->
        <view class="popup-dialog" v-if="Data.cancelShow">
            <view class="popup-dialog-content">
                <view class="title">您确定要取消订单吗，取消后无法恢复</view>
                <view class="button">
                    <view class="cancel" @click="Data.cancelShow = false">取消</view>
                    <view class="confirm" @click="cancelOrderConfirm">确认</view>
                </view>
            </view>
        </view>

        <uni-popup :animation="false" :is-mask-click="false" @change="qrCodePopupChangeHandler" ref="popup">
            <view class="popup-qrCode" :class="{ 'popup-height': type === 'left' || type === 'right' }">
                <view class="popup-qrCode-title">
                    <text>提货码</text>
                </view>
                <canvas style="width: 200px; height: 200px; margin: auto" canvas-id="myQrcode"></canvas>
                <view class="popup-qrCode-code">
                    <text>{{ Data.orderCode }}</text>
                </view>
                <view class="popup-qrCode-info">
                    <text>提货码是唯一提货凭证，请出示给核销员。</text>
                </view>
            </view>
            <view class="popup-qrCode-close">
                <image @click="popup.close()" :src="getImgOssUrl('/ui-prod-2.9.0/close.png')"></image>
            </view>
        </uni-popup>
        <uni-popup ref="alertDialog" type="dialog">
            <uni-popup-dialog
                type="info"
                cancelText="取消"
                confirmText="确认"
                :title="dialog.title"
                :content="dialog.content"
                @confirm="pickedUpConfirm"></uni-popup-dialog>
        </uni-popup>

        <view class="float-box">
            <customerServiceFloat v-if="showServiceFloat" />
        </view>
        <Loading />
        <!-- 隐私监听 -->
        <el-privacy-listener-popup></el-privacy-listener-popup>
    </view>
</template>
<script setup>
import { ref, reactive, computed } from 'vue';
import { onShow, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';
import { floatDivide, getTimeStamp, getImgOssUrl, checkCountdow, translateOrderCode } from '@/commons/utils.js';
import router from '@/router';
import request from '@/request';
import store from '@/store';
import storage from '@/commons/storage';
import NavBar from '@/components/navBar';
import GoodsCard from '@/components/goodsCard';
import CountDown from '@/components/countdown';
import Address from '@/components/address';
import customerServiceFloat from '@/components/customerServiceFloat';
import Loading from '@/components/el-loading';
import { useTrace } from '@/commons/trace';
import subscribe from '@/commons/subscribe';
import drawQrcode from '@/commons/qrcode.js';
import MessageBox from '@/components/messageBox';
import { debounce } from 'lodash';

const messagebox = ref();
const { traceReport } = useTrace();
const popup = ref();
const pageTitle = ref('订单详情');
const alertDialog = ref();
const dialog = reactive({
    title: '',
    content: ''
});
let showdialog = ref(false);

const showServiceFloat = ref(false);

const props = defineProps({
    orderId: {
        type: [String, Number],
        default: ''
    },
    // 1核销扫码 2员工助手
    type: {
        type: Number
    }
});

const goodsStore = store.useGoodsStore();

const statusList = [
    { name: '全部', code: 0, img: getImgOssUrl('/ui-prod-2.0.0/icon_img_status1_1.2.png') },
    { name: '待付款', code: '1', img: getImgOssUrl('/ui-prod-2.0.0/icon_img_status1_1.2.png') },
    { name: '待发货', code: '2', img: getImgOssUrl('/ui-prod-2.0.0/icon_img_status2_1.2.png') },
    // 自提订单
    // { name: '待提货', code: '2', img: getImgOssUrl('/ui-prod-2.8.0/pickup.png') },
    { name: '已发货', code: '3', img: getImgOssUrl('/ui-prod-2.0.0/icon_img_status2_1.2.png') },
    { name: '交易完成', code: '4', img: getImgOssUrl('/ui-prod-2.0.0/icon_img_status3_1.2.png') },
    // 部分发货
    { name: '已发货', code: '5', img: getImgOssUrl('/ui-prod-2.0.0/icon_img_status2_1.2.png') },
    // 拼团中
    { name: '拼团中', code: '6', img: getImgOssUrl('/ui-prod-2.6.0/icon_pin_text.png') },
    // 已关闭
    { name: '已关闭', code: '8' },
    // 交易完成（过售后期）
    { name: '交易完成', code: '9' }
];

const Data = reactive({
    shopId: uni.getStorageSync('ZW_SHOP_ID'),
    cancelShow: false,
    receiptShow: false,
    detailInfo: {},
    goodsList: [],
    orderId: '',
    orderType: '',
    isSelfPickup: '',
    orderSn: ''
});
const getOrderType = type => {
    switch (type) {
        case 1:
            return '普通订单';
        case 2:
            return '秒杀订单';
        case 3:
            // 普通拼团订单
            return '拼团订单';
        case 4:
            // 老带新拼团
            return '拼团订单';
        case 5:
            // 阶梯拼团
            return '拼团订单';
        case 6:
            return '积分商城订单';
        case 7:
            return '满减订单';
        case 8:
            // 满折订单
            return '满减订单';
    }
};

const getDiscountName = () => {
    if (Data.orderType === 1) {
        return '改价优惠';
    }
    if (Data.orderType === 2) {
        return '活动优惠_秒杀';
    }
    if ([3, 4, 5].includes(Data.orderType)) {
        return '活动优惠_拼团';
    }
    if (Data.orderType === 7) {
        return '满减优惠';
    }
    return '其他优惠';
};
const showDiscount = () => {
    if (Data.orderType === 1) {
        return Data?.detailInfo?.discountAmount;
    }
    if (Data.orderType === 2) {
        return Data?.detailInfo?.discountAmount;
    }
    if ([3, 4, 5].includes(Data.orderType)) {
        return Data?.detailInfo?.discountAmount;
    }
    if (Data.orderType === 7) {
        return Data?.detailInfo?.fullReduceAmount;
    }
    return Data?.detailInfo?.discountAmount;
};

const goodsTotal = computed(() => {
    let total = 0;
    if (Data.orderType === 6 && Data.goodsList[0]?.goodsType === 1) {
        total = Data.goodsList.reduce((pre, cur) => pre + cur.totalSellPrice, 0);
    } else {
        total = Data.goodsList.reduce((pre, cur) => pre + cur.total, 0);
    }
    return total;
});

const isLogistics = computed(() => {
    let flag = Data.goodsList.some(el => el.logistics && el.logistics.logisticsNo);
    return flag;
});

const isFinished = computed(() => {
    let nowTime = Date.now();
    let time = getTimeStamp(Data.detailInfo.finishedAt);
    if (nowTime > time) {
        return true;
    } else {
        return false;
    }
});

const getRemarkShow = computed(() => {
    const pintuanStep = Data.detailInfo.orderStatusList?.find(x => x.name === '买家成团') || {};
    if ([3, 4, 5].includes(Data.orderType) && pintuanStep.remark) {
        return pintuanStep.remark;
    }
    return false;
});

const initDetail = async () => {
    let { orderId } = props;
    const requestName = props.type ? 'orderOtherDetailServ' : 'orderDetailServ';
    let res = await request(requestName, { orderId: orderId });
    let info = res.data || {};
    Data.detailInfo = info;
    Data.goodsList = info.goods;
    Data.goodsList.forEach(x => {
        x.goodsNum = x.buyNum;
        x.specValueList = x.skuExtInfo;
        x.goodsPrice = info.orderType === 6 && x.goodsType === 1 ? x.sellPrice : x.goodsPrice;
        // 非积分商城订单使用积分问题，在售后申请使用
        x.sellPoint = x.goodPoints;
        x.goodPoints = info.orderType === 6 ? x.goodPoints : '';
    });
    Data.orderStatus = info.orderStatus;
    Data.orderType = Number(info.orderType);
    Data.isSelfPickup = Number(info.isSelfPickup);
    Data.orderId = info.id;
    Data.orderSn = info.orderSn;
    Data.logisticsFee = info.logisticsFee + info.freeFreightFee;
};

const clickShopCard = val => {
    if ([2, 3].includes(val.goodsType)) {
        router.push({
            path: '/pages-cart/good/virtualDetail',
            query: {
                goodsType: val.goodsType,
                id: val.goodsId
            }
        });
        return;
    }
    router.push({
        path: '/pages-cart/good/index',
        query: {
            goodsNo: val.goodsNo,
            goodsId: val.goodsId,
            from: Data.orderType === 6 ? 'integral' : ''
        }
    });
};

const clickCancelOrder = () => {
    Data.cancelShow = true;
};

const clickReceipt = async () => {
    try {
        await request('checkRefundOrderServ', { orderId: Data.orderId });
    } catch (error) {
        dialog.content = error.data?.msg || '网络错误，请稍后重试~';
        dialog.btnName = '关闭';
        messagebox.value.openPopup();
        return;
    }
    Data.receiptShow = true;
};

const messageBoxConfirm = () => {
    if (dialog.btnName === '取消订单') {
        cancelOrderConfirm();
    } else {
        messagebox?.value?.closePopup();
    }
};

const cancelOrderConfirm = async () => {
    /*************埋点代码开始***********************/
    const traceGoodsList = [];
    Data.goodsList.map(item => {
        traceGoodsList.push({
            productId: item.goodsId,
            productName: item.goodsName,
            skuId: item.skuId
        });
    });
    traceReport('cancel_order', {
        orderId: props.orderId,
        goods: traceGoodsList
    });
    /*************埋点代码结束***********************/
    let params = {
        shopId: Data.shopId,
        orderId: props.orderId
    };
    let res = await request('orderCancelServ', params);
    if (res.data) {
        Data.cancelShow = false;
        messagebox?.value?.closePopup();
        initDetail();
        uni.showToast({
            title: '取消成功',
            icon: 'none'
        });
    }
};

const confirmReceipt = async () => {
    traceReport('sign_order', {
        orderId: props.orderId,
        orderStatus: Data.orderStatus
    });
    let params = {
        orderId: props.orderId
    };
    let res = await request('orderReceiveServ', params);
    if (res.data) {
        initDetail();
        Data.receiptShow = false;
    }
};

const copy = () => {
    uni.setClipboardData({
        data: Data.detailInfo.orderSn,
        success: () => {}
    });
};
// 进店逛逛
const toHome = () => {
    router.switchTab({ url: '/pages/tabbar/home' });
};

// 重新参与
const toGoodsDetail = () => {
    router.push({
        path: '/pages-cart/good/index',
        query: {
            activityId: Data.detailInfo.activityId,
            goodsId: Data.detailInfo.goods[0].goodsId
        }
    });
};

const toPay = debounce(async () => {
    if ([3, 4, 5].includes(Data.orderType) && Data.detailInfo.spellOrderId) {
        try {
            const res = await request('getOffereCheckGroupServ', { spellOrderId: Data.detailInfo.spellOrderId });
            toPayHadCheck();
        } catch (error) {
            // 4000003 该团已失效，请重新选择,4000004 活动已结束，下次早点来哦 4000005 该团已满，请重新选择,4000006 仅新用户可参团，你不符合参团
            switch (error.data.code) {
                case 4000003:
                    uni.showModal({
                        content: error.data.msg,
                        cancelText: '我知道了',
                        confirmText: '重新参与',
                        confirmColor: '#FF4D4F',
                        success: e => {
                            if (e.confirm) {
                                toGoodsDetail();
                            }
                        }
                    });
                    break;
                case 4000004:
                    uni.showModal({
                        content: error.data.msg,
                        confirmText: '进店逛逛',
                        cancelText: '我知道了',
                        confirmColor: '#FF4D4F',
                        success: e => {
                            if (e.confirm) {
                                toHome();
                            }
                        }
                    });
                    break;
                case 4000005:
                    uni.showModal({
                        content: error.data.msg,
                        confirmText: '进店逛逛',
                        cancelText: '我知道了',
                        confirmColor: '#FF4D4F',
                        success: e => {
                            if (e.confirm) {
                                toHome();
                            }
                        }
                    });
                    break;
                default:
                    uni.showModal({
                        content: error.data.msg,
                        confirmText: '我知道了',
                        showCancel: false,
                        confirmColor: '#FF4D4F',
                        success: () => {}
                    });
                    break;
            }
        }
    } else {
        toPayHadCheck();
    }
}, 800);

const toPayHadCheck = () => {
    payChannelList();
    /*************埋点代码开始***********************/
    traceReport('pay_order', {
        orderId: props.orderId,
        payAccount: Data.detailInfo.orderAmountTotal,
        payResult: ''
    });
    /*************埋点代码结束***********************/
};

const payChannelList = async () => {
    await subscribe('order_payment');
    let res = await request('payChannelListServ');
    let payChannel = res.data.payList?.[0];
    wxPay(payChannel);
};

const wxPay = async val => {
    let params = {
        orderSn: Data.orderSn,
        payMethod: val.type
    };
    try {
        let res = await request('payPrepayServ', params);
        let obj = res.data || {};
        // isPaymentApp=true: 商户绑定了支付小程序且开通了宝付支付
        if (res.data?.isPaymentApp) {
            router.push(
                `/pages-cart/cashier/index?appId=${obj.appId}&amount=${Data.detailInfo.orderAmountTotal}&orderSn=${Data.orderSn}&payMethod=${val.type}&orderId=${Data.orderId}&orderType=${Data.orderType}&type=4`
            );
        } else {
            uni.requestPayment({
                provider: 'wxpay',
                timeStamp: obj.timeStamp,
                nonceStr: obj.nonceStr,
                package: obj.package,
                signType: obj.signType,
                paySign: obj.paySign,
                success: function () {
                    router.redirectTo({
                        url: `/pages-cart/paystatus/index?orderId=${Data.orderId}&orderType=${Data.orderType}`
                    });
                },
                fail: function (err) {
                    request('payCancelServ', { orderSn: Data.orderSn, payMethod: val.type });
                    initDetail();
                }
            });
        }
    } catch (err) {
        if ([9002110, 9002109].includes(err.data?.code)) {
            dialog.content = err.data?.msg;
            dialog.btnName = '取消订单';
            messagebox.value.openPopup();
        } else {
            uni.showToast({
                title: err.data?.msg || '网络错误，请稍后重试~',
                icon: 'none',
                duration: 2000
            });
        }
    }
};

const clickRefund = async () => {
    goodsStore.refundGoodsList = Data.goodsList;
    goodsStore.refundGoodsLogisticsFee = Data.detailInfo.logisticsFee + Data.detailInfo.freeFreightFee;
    goodsStore.refundGoodsRefundLogisticsFee = Data.detailInfo.refundLogitsticsFee;
    goodsStore.orderType = Data.orderType;
    goodsStore.isSelfPickup = Number(Data.detailInfo?.isSelfPickup);
    router.push({
        path: '/pages-user/refundgoods/index',
        query: {
            orderId: props.orderId,
            backType: 3
        }
    });
};

const toLogistics = () => {
    let list = Data.goodsList.filter(el => el.logistics && el.logistics.logisticsNo);
    let noList = Data.goodsList.filter(el => !el.logistics);
    goodsStore.logisticsGoodsList = list;
    let packageList = [];
    list.map(el => {
        if (packageList.every(i => i != el.logistics.logisticsNo)) {
            packageList.push(el.logistics.logisticsNo);
        }
    });

    if (packageList.length == 1 && !noList.length) {
        goodsStore.logisticsGoodsInfo = Data.goodsList[0];
        let info = Data.goodsList[0]?.logistics || {};
        router.push({
            path: '/pages-user/logistics/index',
            query: {
                id: info.id,
                logisticCompany: info.logisticsCompany,
                logisticNo: info.logisticsNo
            }
        });
    } else {
        router.push({
            path: '/pages-user/logistics/list'
        });
    }
};

const getStatusImg = code => {
    if (Data.isSelfPickup && code == 3) {
        return getImgOssUrl('/ui-prod-2.8.0/pickup.png');
    }
    let list = statusList;
    let obj = list.find(el => el.code == code) || {};
    return obj.img;
};

const gotoGrow = val => {
    router.push('/pages-cart/group/index?spellOrderId=' + val);
};
const hasCustomerService = async () => {
    let res = await request('openServer');
    storage.set('openServerMes', JSON.stringify(res.data));
    showServiceFloat.value = res.data.orderDetail === 2;
};

const alertDialogHandler = async () => {
    try {
        await request('checkRefundOrderServ', { orderId: Data.orderId });
    } catch (error) {
        dialog.content = error.data?.msg || '网络错误，请稍后重试~';
        dialog.btnName = '关闭';
        messagebox.value.openPopup();
        return;
    }
    if (props.type == 1) {
        dialog.title = '确认核销吗？';
        dialog.content = '核销后不可撤销，请谨慎操作。';
    }
    if (props.type == 2) {
        dialog.title = '确认标记已提货吗？';
        dialog.content = '标记后不可撤销，请谨慎操作。';
    } else {
        dialog.title = '确认已提货吗？';
        dialog.content = '标记提货后不可撤销，请确保已拿到货。';
    }
    alertDialog.value.open();
};

// 我已提货确认
const pickedUpConfirm = () => {
    if (props.type) {
        request('pickUpManagerServ', { orderId: props.orderId }).then(res => {
            uni.showToast({
                title: '核销成功',
                icon: 'none'
            });
            if (props.type == 1) {
                router.navigateBack({ delta: 2 });
            } else {
                initDetail();
            }
        });
    } else {
        request('pickUpMyselfServ', { orderId: props.orderId }).then(res => {
            initDetail();
        });
    }
};

// 查看提货码
const pickingCode = async () => {
    request('orderCodeServ', { orderId: props.orderId }).then(res => {
        Data.orderCode = res.data?.code;
        popup.value.open();
        showdialog.value = true;
        setTimeout(() => {
            drawQrcode({
                width: 200,
                height: 200,
                x: 0,
                y: 0,
                canvasId: 'myQrcode',
                text: Data.orderCode
            });
        }, 100);
    });
};

const qrCodePopupChangeHandler = val => {
    if (!val.show) {
        showdialog.value = false;
        initDetail();
    }
};

/* 拨打电话 */
const copyPhone = () => {
    let phoneNumber = Data.detailInfo?.consigneeMobile;
    uni.makePhoneCall({ phoneNumber, complete: () => {} });
};

onShow(async () => {
    // 从核销入口过来
    if (props.type == 1) {
        pageTitle.value = '核销';
    }
    initDetail();
    hasCustomerService();
});
</script>
<style lang="scss" src="./index.scss" scoped></style>
